package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.CollectionUtils;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    //获取某年某月的第一天
    public static  String getFirstDayOfMonth(Integer year,Integer month){

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,year);    //设置年份
        cal.set(Calendar.MONTH, month-1);  //设置月份
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH); //获取某月最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);   //设置日历中月份的最小天数
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = sdf.format(cal.getTime());
        return firstDayOfMonth;

    }

    //获取某年某月最后一天
    public static String getLastDayOfMonth(Integer year,Integer month){
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,year);    //设置年份
        cal.set(Calendar.MONTH, month-1);  //设置月份
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);  //获取某月最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);    //设置日历中月份的最大天数
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }

    //上周第一天
    public static Date getMonday() {
        LocalDate currentDate = LocalDate.now();
        DayOfWeek currentDayOfWeek = currentDate.getDayOfWeek(); // 获取当前日期是一周中的第几天
        int daysToSubtract = currentDayOfWeek.getValue() + 6; // 计算需要减去的天数
        LocalDate lastWeekFirstDay = currentDate.minusDays(daysToSubtract);
        Instant instant = Timestamp.valueOf(lastWeekFirstDay.atTime(LocalTime.MIDNIGHT)).toInstant();
        Date date = Date.from(instant);
        return date;
    }

    //上周最后一天
    public static Date getSunDay() {
        LocalDate currentDate = LocalDate.now();
        DayOfWeek currentDayOfWeek = currentDate.getDayOfWeek(); // 获取当前日期是一周中的第几天
        int daysToSubtract = currentDayOfWeek.getValue() + 6; // 计算需要减去的天数
        LocalDate lastWeekFirstDay = currentDate.minusDays(daysToSubtract);
        LocalDate lastWeekLastDay = lastWeekFirstDay.plusDays(6);
        Instant instant = Timestamp.valueOf(lastWeekLastDay.atTime(LocalTime.MIDNIGHT)).toInstant();
        Date date = Date.from(instant);
        return date;
    }

    //上个月第一天
    public static Date getLastMonthFirtDay(){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date startTime = cal.getTime();
        return startTime;
    }

    //上个月最后一天
    public static Date getLastMonthLastDay(){
        Calendar calendar=Calendar.getInstance();
        int month=calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month-1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date endTime = calendar.getTime();
        return endTime;
    }

    //当前月第一天
    public static String getMonthFirtDay(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        //获得本月第一天
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String firstDay = sdf.format(calendar.getTime());
        return firstDay;
    }

    //当前月最后一天
    public static String getMonthLastDay(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        //获得本月第一天
        calendar.add(Calendar.MONTH, 0);
        //获得本月最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDay = sdf.format(calendar.getTime());
        return lastDay;
    }

    //上个季度第一天
    public static Date getLastQuarterFirstDay(){
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        // 获取当前季度信息
        int currentQuarter = (calendar.get(Calendar.MONTH) / 3) + 1;
        // 计算上季度的第一天和最后一天
        calendar.add(Calendar.MONTH, -3);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date firstDayOfLastQuarter = calendar.getTime();
        return firstDayOfLastQuarter;
    }

    //上个季度最后一天
    public static Date getLastQuarterLastDay(){
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        // 获取当前季度信息
        int currentQuarter = (calendar.get(Calendar.MONTH) / 3) + 1;
        // 计算上季度的第一天和最后一天
        calendar.add(Calendar.MONTH, 3);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date lastDayOfLastQuarter = calendar.getTime();
        return lastDayOfLastQuarter;
    }


    //当年第一天
    public static String getYearFirstDay(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(date);
        return formattedDate;
    }

    /**
     * 获取上一年年份
     * @return
     */
    public static String getLastYear() {
        SimpleDateFormat formats = new SimpleDateFormat("yyyy");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR,-1);
        Date date =  c.getTime();
        // Date类型转String类型
        String format = formats.format(date);
        return format;
    }

    /**
     * 获取当前年份
     * @return
     */
    public static String getNowYear() {
        SimpleDateFormat formats = new SimpleDateFormat("yyyy");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR,0);
        Date date =  c.getTime();
        // Date类型转String类型
        String format = formats.format(date);
        return format;
    }

    /**
     * 获取下一年年份
     * @return
     */
    public static String getNextYear() {
        SimpleDateFormat formats = new SimpleDateFormat("yyyy");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR,1);
        Date date =  c.getTime();
        // Date类型转String类型
        String format = formats.format(date);
        return format;
    }

    //获取某年某月的第一天
    public static  String getFirstDayOfMonth(String month){
        int year = Integer.parseInt(month.substring(0,4));  //截取出年份，并将其转化为int
        int month1 = Integer.parseInt(month.substring(5,7));    //截去除月份，并将其转为int

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,year);    //设置年份
        cal.set(Calendar.MONTH, month1-1);  //设置月份
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH); //获取某月最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);   //设置日历中月份的最小天数
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = sdf.format(cal.getTime());
        return firstDayOfMonth;

    }

    //获取某年某月最后一天
    public static String getLastDayOfMonth(String month){
        int year = Integer.parseInt(month.substring(0,4));  //截取出年份，并将其转化为int
        int month1 = Integer.parseInt(month.substring(5,7));    //截去除月份，并将其转为int


        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,year);    //设置年份
        cal.set(Calendar.MONTH, month1-1);  //设置月份
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);  //获取某月最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);    //设置日历中月份的最大天数
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }

    //获取某一周的开始时间
    public static Date getWeekStart(int year, int week){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.WEEK_OF_YEAR, week);

        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        Date time = calendar.getTime();
        return time;
    }

    //获取某一年有多少周
    public static int getYearWeekConut(int year) {
        int week = 52;
        try {
            /*Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
            calendar.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
            week = calendar.get(Calendar.WEEK_OF_YEAR);*/
            Map<String, String> timeMap = getWeekRangeMap(year, 53);
            if (!CollectionUtils.isEmpty(timeMap)) {
                String startTime = timeMap.get("startTime");
                if (startTime.substring(0, 4).equals(year + "")) { //判断年度是否相符，如果相符说明有53个周。
                    week = 53;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return week;
    }

    /**
     * 获取某年某周的时间跨度
     * @param year
     * @param week
     * @return
     */
    public static Map<String, String> getWeekRangeMap(int year, int week) {
        Map<String, String> timeMap = new HashMap<String, String>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
        calendar.setMinimalDaysInFirstWeek(4);//可以不用设置
        int weekYear = calendar.get(Calendar.YEAR);//获得当前的年
        calendar.setWeekDate(weekYear, week, 2);//获得指定年的第几周的开始日期
        Date time=calendar.getTime();
        String startTime = new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00";
        timeMap.put("startTime",startTime);
        calendar.setWeekDate(weekYear, week, 1);//获得指定年的第几周的结束日期
        time=calendar.getTime();
        String endTime = new SimpleDateFormat("yyyy-MM-dd").format(time)+" 23:59:59";
        timeMap.put("endTime",endTime);
        return timeMap;
    }

    public static void main(String[] args) {
        int yearWeekConut = DateUtils.getYearWeekConut(2023);
        System.out.println(yearWeekConut);
        Map<String, String> weekRangeMap = DateUtils.getWeekRangeMap(2023, 1);
        System.out.println(weekRangeMap.get("startTime"));
        System.out.println(weekRangeMap.get("endTime"));
    }



}
